package com.enba.boot.security.filter;

import com.enba.boot.core.base.Result;
import com.enba.boot.redis.RedisOperator;
import com.enba.boot.security.enums.AuthStatusEnum;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

  private final RedisOperator redisOperator;

  public CaptchaFilter(RedisOperator redisOperator) {
    this.redisOperator = redisOperator;
  }

  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    if (request.getMethod().equals("POST")
        && (request.getRequestURI().equals("/login")
            || request.getRequestURI().equals("/register"))) {
      // 获取参数中的验证码
      String key = request.getParameter("key") == null ? "" : request.getParameter("key");
      String code = request.getParameter("code") == null ? "" : request.getParameter("code");
      // 获取缓存中的验证码
      String redisCode = redisOperator.get("captcha:" + key, String.class);
      // 判断验证码
      if (redisCode == null) {
        Result.render(
            response,
            Result.err(
                AuthStatusEnum.CAPTCHA_EXPIRE.getCode(), AuthStatusEnum.CAPTCHA_EXPIRE.getMsg()));
      } else if (!redisCode.equals(code.toLowerCase())) {
        Result.render(
            response,
            Result.err(
                AuthStatusEnum.CAPTCHA_ERROR.getCode(), AuthStatusEnum.CAPTCHA_ERROR.getMsg()));
      } else {
        chain.doFilter(request, response);
      }
    } else {
      chain.doFilter(request, response);
    }
  }
}
